package com.nervenets.web.controller.handler.admin.order;

import com.nervenets.utils.JodaUtils;
import com.nervenets.web.controller.handler.SessionHandler;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.enumeration.OrderStatus;
import com.nervenets.web.enumeration.Role;
import com.nervenets.web.hibernate.domain.user.Order;
import com.nervenets.web.redis.utils.ISyncExecutor;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

public class OrderExpressHandler extends SessionHandler<OrderExpressParams> {
    @Override
    public ArrayList<Role> allowRoles() {
        return Role.administrator();
    }

    @Override
    public boolean needLog() {
        return false;
    }

    @Override
    public String handle(OrderExpressParams params, HttpServletRequest request) throws Exception {
        return (String) redisSyncLocker.idLock(params.getOrderId(), o -> {
            Order order = userDao.findById(params.getOrderId(), Order.class);
            if (null == order) return errorMessage(MessageCode.code_404, "订单不存在");
            order.getExtra().setExpressName(params.getExpressName());
            order.getExtra().setExpressNumber(params.getExpressNumber());
            order.getExtra().setExpressTime(JodaUtils.getTimestamp());
            order.setStatus(OrderStatus.delivery);
            userDao.saveOrUpdate(order);
            return successMessage(order);
        });
    }

    @Override
    public String result() throws Exception {
        return successMessage();
    }
}
